const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { info } = require("ee-core/log");

/**
 * 生成组织树和用户对象
 * @param {string} dirPath 文件夹路径
 * @param {string} parentId 父级组织的ID
 * @returns {object} 包含组织树和用户列表的对象
 */
function generateTree (dirPath, parentId = '0') {
	const orgTree = []; // 组织树
	const users = [];    // 用户列表

	// 读取文件夹内容
	const items = fs.readdirSync(dirPath);

	items.forEach(item => {
		const itemPath = path.join(dirPath, item);
		const stat = fs.statSync(itemPath);

		if (stat.isDirectory()) {
			// 如果是文件夹，生成组织对象
			const orgId = uuidv4().replace(/-/g, '').substring(0, 13); // 生成唯一的ID
			const orgNode = {
				id: orgId,
				name: item,
				parentId: parentId,
				children: [],
				path: itemPath,
			};

			// 递归处理子文件夹
			const { orgTree: subTree, users: subUsers } = generateTree(itemPath, orgId);
			orgNode.children = subTree;
			users.push(...subUsers);
			orgTree.push(orgNode);
		} else if (path.extname(item) === '.docx') {
			// 如果是 .docx 文件，生成用户对象
			const userId = 'u' + uuidv4().replace(/-/g, '').substring(0, 13); // 生成唯一的用户ID
			const userName = path.basename(item, '.docx'); // 文件名作为用户名字
			const user = {
				id: userId,
				filePath: itemPath,
				deptId: parentId,
				name: userName,
			};
			users.push(user);
		}
	});

	return { orgTree, users };
}


function sleep (ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

module.exports = {
	generateTree,
}
